﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using ThridGroup.ERP.DTO.ProductionSystem;
using ThridGroup.ERP.DTO.ProductionSystem.RepairOrderDto;
using ThridGroup.ERP.ProductionSystem;
using System.Linq;

namespace ThridGroup.ERP.Web.Controllers.ProductionSystem
{ 
    
    /// <summary>
    /// 设备台账控制器
    /// </summary>
    [Route("DeviceLedger")]
    public class DeviceLedgerController : Controller
    {
        private readonly IDeviceLedgerServices _deviceLedgerServices;
        private readonly IRepairOrderServices _repairOrderServices;

        public DeviceLedgerController(IDeviceLedgerServices deviceLedgerServices, IRepairOrderServices repairOrderServices) 
        {
            _deviceLedgerServices = deviceLedgerServices;
            _repairOrderServices = repairOrderServices;
        }

        #region 设备台账相关方法

        [HttpGet("DeviceLedgerView")]
        public IActionResult DeviceLedgerView()
        {
            return View();
        }

        /// <summary>
        /// 获取设备台账列表
        /// </summary>
        [HttpPost("List")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> GetList(int page = 1, int limit = 10, string deviceCode = null, string deviceName = null, string equipmentTypeCode = null)
        {
            try
            {
                var result = await _deviceLedgerServices.GetDeviceLedgerList(page, limit, deviceCode, deviceName, equipmentTypeCode);
                return Json(new { code = 0, msg = "success", count = result.TotalCount, data = result.Items });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "获取列表失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 添加设备台账
        /// </summary>
        [HttpPost("AddDeviceLedger")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> AddDeviceLedger(CreateDeviceLedgerDto input)
        {

            try
            {
                var id = await _deviceLedgerServices.AddDeviceLedger(input);
                return Json(new { code = 0, msg = "添加成功", id });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "添加失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 获取设备分类树
        /// </summary>
        [HttpGet("GetEquipmentTypeTree")]
        public async Task<IActionResult> GetEquipmentTypeTree()
        {
            try
            {
                var result = await _deviceLedgerServices.GetEquipmentTypeTreeAsync();
                
                // 转换为Layui树格式
                var treeData = result.Select(item => new
                {
                    id = item.EquipmentTypeCode,
                    title = item.EquipmentTypeName,
                    spread = false // 默认收起
                }).ToList();
                
                return Json(new { code = 0, msg = "success", data = treeData });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "获取设备分类失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 获取设备分类列表
        /// </summary>
        [HttpGet("GetEquipmentTypeList")]
        public async Task<IActionResult> GetEquipmentTypeList()
        {
            try
            {
                var result = await _deviceLedgerServices.GetEquipmentTypeListAsync();
                return Json(new { code = 0, msg = "success", data = result });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "获取设备分类列表失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 删除设备台账
        /// </summary>
        [HttpPost("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                await _deviceLedgerServices.DeleteDeviceLedger(id);
                return Json(new { code = 0, msg = "删除成功" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "删除失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 修改设备台账
        /// </summary>
        [HttpPost("Update")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Update(CreateDeviceLedgerDto input)
        {
            if (!ModelState.IsValid)
            {
                return Json(new { code = 1, msg = "请填写必填项" });
            }

            try
            {
                var id = await _deviceLedgerServices.UpdateDeviceLedger(input);
                return Json(new { code = 0, msg = "修改成功", id });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "修改失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 根据ID获取单条设备台账信息（用于编辑反填）
        /// </summary>
        [HttpGet("GetById")]
        public async Task<IActionResult> GetById(int id)
        {
            try
            {
                var result = await _deviceLedgerServices.GetDeviceLedgerById(id);
                return Json(new { code = 0, msg = "success", data = result });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "获取设备台账失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 批量删除设备台账
        /// </summary>
        [HttpPost("BatchDelete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> BatchDelete(int[] ids)
        {
            if (ids == null || ids.Length == 0)
            {
                return Json(new { code = 1, msg = "请选择要删除的设备" });
            }

            try
            {
                foreach (var id in ids)
                {
                    await _deviceLedgerServices.DeleteDeviceLedger(id);
                }
                return Json(new { code = 0, msg = $"成功删除{ids.Length}条记录" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "批量删除失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 检查设备编号是否已存在
        /// </summary>
        [HttpGet("CheckDeviceCodeExists")]
        public async Task<IActionResult> CheckDeviceCodeExists(string deviceCode)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(deviceCode))
                {
                    return Json(new { code = 1, msg = "设备编号不能为空" });
                }

                // 查询具有相同设备编号的记录
                var result = await _deviceLedgerServices.GetDeviceLedgerList(1, 1, deviceCode, null, null);
                bool exists = result.TotalCount > 0;

                return Json(new { code = 0, exists = exists });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "检查设备编号失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 生成设备编号
        /// </summary>
        [HttpGet("GenerateDeviceCode")]
        public IActionResult GenerateDeviceCode()
        {
            try
            {
                // 生成格式：年月日+4位随机数
                var today = DateTime.Now;
                string deviceCode = today.ToString("yyyyMMdd") + new Random().Next(1000, 9999).ToString();

                return Json(new { code = 0, deviceCode = deviceCode });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "生成设备编号失败：" + ex.Message });
            }
        }

        #endregion

        #region 维修单相关方法

        /// <summary>
        /// 维修单视图
        /// </summary>
        [HttpGet("RepairOrderView")]
        public IActionResult RepairOrderView()
        {
            return View();
        }

        /// <summary>
        /// 创建维修单视图
        /// </summary>
        [HttpGet("CreateRepairOrderView")]
        public IActionResult CreateRepairOrderView()
        {
            return View();
        }

        /// <summary>
        /// 修改维修单视图
        /// </summary>
        [HttpGet("UpdateRepairOrderView")]
        public IActionResult UpdateRepairOrderView()
        {
            return View();
        }

        /// <summary>
        /// 获取维修单列表
        /// </summary>
        [HttpPost("RepairOrderList")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> GetRepairOrderList(GetRepairOrderDto input)
        {
            try
            {
                var result = await _repairOrderServices.QueryRepairOrder(input);
                return Json(new { code = 0, msg = "success", count = result.TotalCount, data = result.Data });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "获取维修单列表失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 添加维修单
        /// </summary>
        [HttpPost("AddRepairOrder")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> AddRepairOrder(QueryRepairOrderDto input)
        {
            if (!ModelState.IsValid)
            {
                return Json(new { code = 1, msg = "请填写必填项" });
            }

            try
            {
                var result = await _repairOrderServices.CreateRepairOrder(input);
                return Json(new { code = 0, msg = "添加成功", result });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "添加失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 修改维修单
        /// </summary>
        [HttpPost("UpdateRepairOrder")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> UpdateRepairOrder(QueryRepairOrderDto input)
        {
            if (!ModelState.IsValid)
            {
                return Json(new { code = 1, msg = "请填写必填项" });
            }

            try
            {
                var result = await _repairOrderServices.UpdateRepairOrder(input);
                return Json(new { code = 0, msg = "修改成功", result });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "修改失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 根据ID获取维修单信息
        /// </summary>
        [HttpGet("GetRepairOrderById")]
        public async Task<IActionResult> GetRepairOrderById(int id)
        {
            try
            {
                var result = await _repairOrderServices.GetRepairOrderById(id);
                return Json(new { code = 0, msg = "success", data = result });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "获取维修单失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 批量删除维修单
        /// </summary>
        [HttpPost("BatchDeleteRepairOrder")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> BatchDeleteRepairOrder(int[] ids)
        {
            if (ids == null || ids.Length == 0)
            {
                return Json(new { code = 1, msg = "请选择要删除的维修单" });
            }

            try
            {
                await _repairOrderServices.BatchDeleteRepairOrder(ids.ToList());
                return Json(new { code = 0, msg = $"成功删除{ids.Length}条记录" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "批量删除失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 修改维修单状态
        /// </summary>
        [HttpPost("UpdateRepairOrderStatus")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> UpdateRepairOrderStatus(int id)
        {
            try
            {
                var result = await _repairOrderServices.GetRepairOrderStatus(id);
                return Json(new { code = 0, msg = "状态修改成功", result });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "状态修改失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 生成维修单编号
        /// </summary>
        [HttpGet("GenerateRepairOrderCode")]
        public IActionResult GenerateRepairOrderCode()
        {
            try
            {
                // 生成格式：WX + 年月日 + 4位随机数
                var today = DateTime.Now;
                string repairOrderCode = "WX" + today.ToString("yyyyMMdd") + new Random().Next(1000, 9999).ToString();

                return Json(new { code = 0, repairOrderCode = repairOrderCode });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "生成维修单编号失败：" + ex.Message });
            }
        }

        #endregion
    }
}
